<?
ini_set("display_errors",1);
include($_SERVER['DOCUMENT_ROOT'].'/includes/functions.inc.php');
include($_SERVER['DOCUMENT_ROOT'].'/config.php');
include($_SERVER['DOCUMENT_ROOT'].'/groups/database.php');
include($_SERVER['DOCUMENT_ROOT'].'/filter.libs.php');

$bits = explode('.',$_SERVER['SERVER_NAME']);
$domain = $bits[0];

$row = getRow("SELECT portal_id,title,user_id,realname,readable,public FROM portal INNER JOIN user USING (user_id) WHERE domain = ".dbQuote($domain)." AND status_id = 1");

if (empty($row['portal_id'])) {
	header("HTTP/1.0 404 Not Found");
	print "<html><head>";
	print "<title>Not found!</title>";
	print "</head><body>";
	print "<p>The page you are looking for is not available</p>";
	
	print "<p><a href=\"http://www.geographs.org/portals/?ref=$domain\">Try the Portal Homepage</a></p>";
	print "</body></html>";
	print str_repeat(" ",500);
	exit;
}

$id = intval($row['portal_id']);
$title = $row['title'];

$row['count'] = count_active($id);

$page_title = "Search";
if (empty($_GET['inner'])) {
	include($_SERVER['DOCUMENT_ROOT'].'/header.inc.php');
} else {
	?><html>
	<head>	<link rel="stylesheet" type="text/css" href="/style.css" />
	</head>
	<body><?
}


if ($row['public'] != 'Y') {
	print "<p>NOTE: Only Public Portals work with this feature. This might change in the future.</p>";
	
	if (empty($_GET['inner'])) {
		include($_SERVER['DOCUMENT_ROOT'].'/footer.inc.php');
	}

	exit;
}


#########################


if (!empty($_GET['q']) && $_GET['q'] == 'search keywords...') {
	$_GET['q'] ='';
}

include($_SERVER['DOCUMENT_ROOT'].'/geograph/sphinxwrapper.class.php'); 
	
$CONF['sphinx_host'] = "localhost";
$CONF['sphinx_port']= 3312;
$CONF['sphinx_index']= "portalimages";

if (!empty($_GET['q'])) {
 
	$q=trim($_GET['q']);
	
		$q = preg_replace('/\b(day|month|year):/','taken$1:',$q);
		$q = preg_replace('/\b(monthname):/','month:',$q);
		$q = preg_replace('/\b(gridref):/','grid_reference:',$q);
		$q = preg_replace('/\b(category):/','imageclass:',$q);
		$q = preg_replace('/\b(description):/','comment:',$q);
		$q = preg_replace('/\b(name):/','realname:',$q);
	
	$sphinx = new sphinxwrapper($q);

	$q = $sphinx->q;
} else {
	$sphinx = new sphinxwrapper($q);
	$q = '';
}
 
 
if (!empty($_GET['lat'])) {
	$cl = $sphinx->_getClient();

 	$d = empty($_GET['d'])?10:min(20,intval($_GET['d'])); //km
 	
 	$cl->SetGeoAnchor('wgs84_lat', 'wgs84_long', deg2rad($_GET['lat']), deg2rad($_GET['long']) );
 	$cl->SetFilterFloatRange('@geodist', 0.0, floatval($d*1000));
 
 	$sphinx->setSort("@geodist ASC, @relevance DESC, @id DESC");
 	
 	$title = sprintf("Images within %dkm of %.6f,%.6f.",$d,$_GET['lat'],$_GET['long']);
}
 
if (empty($_GET['inner'])) {
?>
<form method="get" style="background-color:#cccccc;padding:3px;">

	<div>Search: <input type="text" name="q" size="40" value="<? echo htmlentities($sphinx->qclean); ?>">
	<input type="submit" value="Search"> <small>(<a href="search.php">Search Help</a>)</small></div>
</form>
<?
}

if (!empty($_GET['q']) || !empty($_GET['lat'])) {
 
	$sphinx->pageSize = $pgsize = 10;

	
	$pg = (!empty($_GET['page']))?intval(str_replace('/','',$_GET['page'])):0;
	if (empty($pg) || $pg < 1) {$pg = 1;}
	
	$cacheid .=".".$pg;
	
		
		$offset = (($pg -1)* $sphinx->pageSize)+1;
		
		if ($offset < (1000-$pgsize) ) { 
			#$sphinx->processQuery();
		
			$cl = $sphinx->_getClient();
			
			$cl->setFilter('portal_id',array($id));
			
			$ids = $sphinx->returnIds($pg,'portalimages');	
			
			if (!empty($ids) && count($ids)) {
				
				$sql = array();
				$sql['columns'] = 'gridimage_id,title,realname,user_id,grid_reference,comment,imagetaken,imageclass';
				$sql['tables'] = array();
				
				$sql['tables'][] = "p2.gridimage{$id}_bi_view AS gi";
				
				$sql['wheres'] = array();
				$sql['wheres'][] = "gridimage_id IN(".join(",",$ids).")";
				
				$sql['order']= 'NULL'; //we going to reorder anyway
				$sql['limit'] = $sphinx->pageSize;

			
				
				$query = sqlMakeQuery($sql);
				$rows = getAssoc($query);
				
				
				$docs = array();
				foreach ($ids as $idx => $id) {
					$c = $rows[$id];
					$s = array();
					
					if ($c['comment']) 
						$s[] = strip_tags($c['comment']);
					if ($c['imageclass']) 
						$s[] = "Category: ".$c['imageclass'];
			
					$docs[$idx] = implode('<br/>',$s);
				}
				$reply = $sphinx->BuildExcerpts($docs, 'linksdir', $sphinx->q);

				$final = min($offset+$sphinx->pageSize-1,$sphinx->resultCount);
				print "<div style=\"float:right\">{$offset}..{$final} of {$sphinx->resultCount}</div>";
				
				print "Results for '{$sphinx->qclean}' :<ol class=\"results\" start=\"$offset\">";
				foreach ($ids as $idx => $id) {
					$c = $rows[$id];
					if ($c) {
					$c['gridimage_id'] = $id;
					?>
					<div style="clear:left; border-top:1px solid #eeeeee">
					  <div style="float:left;position:relative; width:130px; margin-right:10px">
					  <div align="center">
					  <a title="<? ehec('grid_reference'); ?> : <? ehec('title'); ?> by <? ehec('realname'); ?> - click to view full size image" href="http://www.geograph.org.uk/photo/<? echo $c['gridimage_id']; ?>"><img src="<? echo gGUc($c); ?>"/></a></div>
					  </div>

					  <? echo $offset; ?>. <big><a href="http://www.geograph.org.uk/gridref/<? ehec('grid_reference'); ?>"><tt><? ehec('grid_reference'); ?></tt></a>
					  <b><a href="http://www.geograph.org.uk/photo/<? echo $c['gridimage_id']; ?>"><? ehec('title'); ?></a></b></big>
					   by <a href="<? echo linktoself(array('bi_id'=>$c['user_id'],'delete'=>'page')); ?>"><? ehec('realname'); ?></a><br/>

					  Taken: <?
						$bits = explode('-',$c['imagetaken']);
						$str = '';
						foreach ($bits as $idxx => $bit) {
							if ($idxx > 0) { echo "-"; $str .= '-'; }
							$str .= $bit;
							print "<a href=\"".linktoself(array('taken'=>$str,'delete'=>'page'))."\">$bit</a>";
						}
						
					if (!empty($reply[$idx]) && strlen($reply[$idx]) > 2) {
						print "<br/>{$reply[$idx]}";
					} else {
					  ?>
					  Category: <a href="<? echo linktoself(array('category'=>$c['imageclass'],'delete'=>'page')); ?>"><? ehec('imageclass'); ?></a> 
					  <? if (!empty($c['comment'])) {
						print "<br/>".hec('comment');
					  } 
					}
					  
					  ?>
					  <br style="clear:left"/>
					</div>
					<?
					} else {
						?>
						<div style="clear:left; border-top:1px solid #eeeeee">
							 <? echo $offset; ?>. Image <a href="http://www.geograph.org.uk/photo/<? echo $id; ?>">http://www.geograph.org.uk/photo/<? echo $id; ?></a> not available in this portal at the moment.
						</div>
						<?
					}
					
					$offset++;
				}
				print "</ol>";
				
				if ($sphinx->resultCount > $sphinx->pageSize) {
					print " &middot; &nbsp; ";
					if ($pg > 1) {
						$last = $pg-1;
						$link = linktoself(array('page'=>$last));
						print "<a href=\"$link\">&lt; &lt; <b>Prev page</b> </a> &nbsp; &middot; ";
					}
					if ($pg < $sphinx->numberOfPages) {
						$next = $pg+1;
						$link = linktoself(array('page'=>$next));
						print " &nbsp; <a href=\"$link\"><b>Next page</b> &gt;&gt;</a> &nbsp; &middot;";
					}
				}
		
				print "<br style='clear:both'><p class=\"message\">{$sphinx->query_info}</p>";
				
				
				
				
				
				
			} else {
				print "<p>No results for your query.</p>";
							
			}
			
			
			
		} else {
			print "Search will only return 1000 results - please refine your search";
		
		}
	

} else {
?>
	<ul>
		<li>Separate multiple keywords with spaces, all keywords are required (ie AND)</li>
		<li>Only matches whole words, punctuation is not searchable</li>
		<li>Not case sensitive</li>
		<li><b>Looking for exact match?</b><br/>&nbsp; Prefix a keyword with <tt>=</tt> (otherwise <tt>bridge</tt> matches bridges, bridging etc)</small></li>
		<li><b>Currently searches</b><ul>
			<li>title, description, category, hectad and myriad</li>
		</ul></li>
		<li>Can match phrases [ <tt>"road bridge"</tt> ]</li>
		<li>Can use OR between keywords <span class="nowrap">[ <tt>bridge OR bont OR pont</tt> ]</span></li>
		<li>Can exclude words/terms [ <tt>canal -river</tt> ] or [ <tt>river -"road bridge"</tt> ]</li>
		<li>Instead run a ANY search [ <tt>~bridge road river</tt> ]</li>
	</ul>
	
	<b>Field search Examples...</b>
	<ul>
		<li><tt>title:leaderboard</tt></li>
		<li><tt>hectad:TQ75</tt></li>
		<li><tt>grid_reference:SH5050</tt></li>
		<li><tt>description:test</tt></li>
	</ul>
	
	<p>(Note: it is recommended to put fields at the end of the query - i.e. normal keywords should be first) </p>
	
	<p><a href="http://www.geograph.org.uk/article/Word-Searching-on-Geograph#other-features">Other Features...</a></p>
<?

}


if (empty($_GET['inner'])) {
	include($_SERVER['DOCUMENT_ROOT'].'/footer.inc.php');
}
